package o2o.delivery.utils;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * DATE: 18/9/3
 *
 * @author: wan
 */
public class DeliveryHttpClientUtil {

    private static Logger logger = LoggerFactory.getLogger(DeliveryHttpClientUtil.class);
    public static final CloseableHttpClient httpClient;

    public static final String CHARSET = "UTF-8";

    public static final int DEF_CONN_TIMEOUT = 4000;
    public static final int DEF_READ_TIMEOUT = 4000;

    static {
        RequestConfig config = RequestConfig.custom().setConnectTimeout(300000).setSocketTimeout(300000).build();
        httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
    }


    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            //注意在传送json数据时， Content-Type的值
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("connection", "keep-alive");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.write(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    public static String doPost(String url, Map<String, Object> params) {
        return doPost(url, params, CHARSET, null);
    }

    public static String doPost(String url, Map<String, Object> params, String token) {
        return doPost(url, params, CHARSET, token);
    }

    /**
     * HTTP Post 获取内容
     *
     * @param url     请求的url地址 ?之前的地�?
     * @param params  请求的参�?
     * @param charset 编码格式
     * @return 页面内容
     */
    public static String doPost(String url, Map<String, Object> params, String charset, String token) {
        if (StringUtils.isBlank(url)) {
            return null;
        }
        HttpPost httpPost = null;
        CloseableHttpResponse response = null;
        try {
            List<NameValuePair> pairs = null;
            if (params != null && !params.isEmpty()) {
                pairs = new ArrayList<NameValuePair>(params.size());
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    if (entry.getValue() != null) {
                        pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
                    }
                }
            }
            httpPost = new HttpPost(url);
            httpPost.setHeader("serialSeq", "1212121");
            httpPost.setHeader("verChl", "0.0.1");
            httpPost.setHeader("sendChl", "hzsmk.test");
            httpPost.setHeader("sendClient", "hellohzsmk");
            httpPost.setHeader("sendDev", "121aqweq");
            // httpPost.setHeader("Content-Type", "form-data");
            // httpPost.addHeader("Content-type", "application/x-www-form-urlencoded");
            httpPost.addHeader("Content-type", "application/json");
            if (StringUtils.isNotEmpty(token)) {
                // System.out.println("本次使用的token:" + token);
                httpPost.addHeader("access_token", token);
            }
            if (pairs != null && pairs.size() > 0) {
                httpPost.setEntity(new UrlEncodedFormEntity(pairs, CHARSET));
            }
            response = httpClient.execute(httpPost);

            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                httpPost.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            HttpEntity entity = response.getEntity();
            String result = null;
            if (entity != null) {
                result = EntityUtils.toString(entity, "utf-8");
            }
            EntityUtils.consume(entity);
            response.close();
            return result;

        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("httpclient请求失败");
        } finally {
            if (httpPost != null) httpPost.releaseConnection();
        }
    }
}
